<?php
/**
 * Created by PhpStorm.
 * User: xrr
 * Date: 18-8-31
 * Time: 下午6:22
 */

namespace App\Http\Controllers;


use App\Apply;
use App\Mail\applySend;
use App\User;
use Carbon\Carbon;
use http\Url;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Validator;

class ApplyController extends  Controller
{
    public function index(){
        $date=[
            0 => '星期日',
            1 => '星期一',
            2 => '星期二',
            3 => '星期三',
            4 => '星期四',
            5 => '星期五',
            6 => '星期六',
        ];
        $dateDict=[];
        $toDay=Carbon::today();
        for($i = 0 ;$i < 7 ; $i++ ){
            $toDayWeek=Carbon::parse($toDay)->dayOfWeek;
            $dateDict[$date[$toDayWeek]]=$toDay->toDateString();
            $toDay=$toDay->addDay();
        }

        $applies=Apply::where('apply_time','>=',Carbon::today())->whereNotIn('check_status',[Apply::APPLY_OVERDUE,Apply::APPLY_REFUSED])->get();

        $moring=['8:00-9:00','9:00-10:00','10:00-11:00','11:00-12:00','12:00-13:00'];

        $afternoon=['13:00-14:00', '14:00-15:00','15:00-16:00','16:00-17:00','17:00-18:00'];

        $evening=['18:00-19:00','19:00-20:00','20:00-21:00','21:00-22:00'];

        $viewData=[
            'dateDict'  => $dateDict,
            'applies'   => $applies->toArray(),
            'moring'    => $moring,
            'afternoon' => $afternoon,
            'evening'   => $evening,
        ];
        return view('apply',$viewData);
    }

    public function apply(Request $request){

       $vaResult=$this->valida($request->all());

       if($vaResult['code']!=200){

           return api_response('validate_fail',[],$vaResult['message']);
       }


       $handFileRes=$this->handleFile($request->file('image'));

       if($handFileRes['code']!=200){
           return api_response('fail',[],$handFileRes['message']);
       }
       $storeData=$request->all();

       $storeData['file']=$handFileRes['url'];

       $res=$this->store($storeData);

       if($res['code']!=200){
           return api_response('fail',[],$res['message']);
       }

       $this->emailTeacher($res['apply'],$request);

       return api_response('ok',$res['apply']->toArray(),$res['message']);

    }

    public  function valida($vaData){

        $va=Validator::make($vaData,[
            'applyer_name'    => 'required',
            'stu_id'          => 'required|digits:11',
            'phone'           => 'required|digits:11',
            'email'           => 'required|email',
            'department'      => 'required|string',
            'meeting_subject' => 'required|string',
            'image'           => 'required|image',
            'apply_time'      => 'date|required',
            'day'             => 'string|required',
            'exact_time'      => 'required',
        ], [
            'applyer_name.required'    => '申请人名字必填',
            'stu_id.digits'            => '学号的格式不正确',
            'phone.digits'             => '电话号码的格式不正确',
            'email.required'           => '请输入邮箱地址',
            'email.email'              => '邮箱地址格式不正确',
            'department.required'      => '审核部门不能为空',
            'meeting_subject.required' => '会议主题不能为空',
            'image.image'              => '上传审核资料必须是图片格式',
            'apply_time.date'          => '申请时间必须是时间格式',
            'exact_time.required'      => '请选择申请的时间段',

        ]);

        if($va->fails()){
            return ['code'=>'1100','message'=>$va->errors()->first()];
        }
        return ['code'=>'200'];
    }

    public  function handleFile($file){

        if(!$file->isValid()){
            return ['code'=>1100,'meesage'=>'文件无效'];
        }
        $fileName = $file->hashName();
        $filePath = date('Ymd').'/';
        $savePath = base_path('public/static/'.$filePath);
        if(! is_dir($savePath) && ! mkdir($savePath, 0777, true)) {
            return ['code'=>1000,'meesage'=>'系统出错'];;
        }



        $file->move($savePath, $fileName);

        return [
            'code'         => 200,
            'name'         => $file->getClientOriginalName(),
            'size'         => $file->getClientSize(),
            'path'         => $savePath.$fileName,
            'url'          => rtrim(config('app.domain.static'), '/').'/'.$filePath.$fileName,
        ];

    }
    public  function store($data){

        $apply=new Apply;
        $apply->check_status=-1;
        $apply->exact_time=$data['exact_time'];
        if(!$apply->fill(array_except($data,'exact_time'))->save()){
            return ['code'=>1000,'message'=>'系统出错'];
        }

        return ['code'=>200,'apply'=>$apply,'message'=>'已经成功申请'];
    }

    public function emailTeacher(Apply $apply,$request){

        $when = Carbon::now()->addMinutes(1);

        $user=User::all()->first();

        $passUrl=url('pass_apply')."?id=".$apply->id.'&sid='.$request->session()->getId();
        $denyUrl=url('deny_apply')."?id=".$apply->id.'&sid='.$request->session()->getId();

        try {
            Mail::to($user->email)
                ->later($when, new applySend($apply, $user, "email.sendTeacher",$passUrl,$denyUrl));

        }catch (\Exception $e){
            Mail::to($user->email)
                ->later($when, new applySend($apply, $user, "email.sendTeacher",$passUrl,$denyUrl));
        }

        return;
    }

    public function downLoadApplyFile(Request $request){


        return response()->download("/var/www/209AF/public/download/15栋209会议室申请书（易班版）.docx", "15栋209会议室申请书(易班版).docx");

    }


}